import wx,os
from PIL import Image

ID_ONE=100
ID_MORE=101
ID_CREATE=102

class ImgDialog(wx.Dialog):
    '''
    图片处理
    '''
    def __init__(self,parent,id):

        self.app=wx.GetApp()
        wx.Dialog.__init__(self,parent,id,'图片转换',size=(500,600))

        self.file=""
        self.fileList=[]
        self.sourcePath=os.getcwd()
        self.imgType="png"
        #20
        self.width=20
        self.height=20

        oneBtn = wx.Button(self,ID_ONE,label='单文件')
        oneBtn.Bind(wx.EVT_BUTTON,self.one)

        moreBtn = wx.Button(self,ID_MORE,label='目录')
        moreBtn.Bind(wx.EVT_BUTTON,self.more)

        self.createBtn=wx.Button(self,ID_CREATE,label='生成')
        self.createBtn.Bind(wx.EVT_BUTTON,self.create)
        self.createBtn.Disable()

        self.showContext=wx.TextCtrl(self,style=wx.TE_MULTILINE|wx.TE_AUTO_URL|wx.TE_RICH2|wx.TE_READONLY,size=(380, 400))
        self.layout=wx.BoxSizer(wx.VERTICAL)

        listDerection = ['png','jpg','jpeg','gif']
        self.radioDerection = wx.RadioBox(self,-1,'图片类型',choices=listDerection,style=wx.RA_SPECIFY_COLS)
        self.radioDerection.Bind(wx.EVT_RADIOBOX,self.OnDerection)

        box = wx.BoxSizer()
        box.Add(oneBtn,proportion = 1,flag = wx.EXPAND|wx.ALL,border=20)
        box.Add(moreBtn,proportion = 1,flag = wx.EXPAND|wx.ALL,border=20)
        box.Add(self.createBtn,proportion = 1,flag = wx.EXPAND|wx.ALL,border=20)


        #proportion 填充比例 0 m默认
        self.layout.Add(box,proportion = 0,flag = wx.ALIGN_CENTER ,border = 2)
        self.layout.Add(self.radioDerection,proportion=0,flag=wx.ALIGN_CENTER,border=2)
        self.layout.Add(self.showContext,proportion=0,flag = wx.ALIGN_CENTER|wx.TOP,border = 20)
        self.SetSizer(self.layout)

    def one(self,event):
        wildcard = 'All files(*.*)|*.*'
        dialog = wx.FileDialog(None,'文件选择',os.getcwd(),'',wildcard,wx.FD_OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            self.file=dialog.GetPath()
            dialog.Destroy()
            self.showContext.AppendText("添加文件"+self.file)
            self.createBtn.Enable()

    def more(self,event):
        dialog = wx.DirDialog(None,'文件夹选择',self.sourcePath,wx.FD_OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            self.sourcePath=dialog.GetPath()
            list = foundFile(dialog.GetPath(),fileNameEnd=self.imgType)
            dialog.Destroy()
            for one in list:
                self.fileList.append(one)
                self.showContext.AppendText("添加文件"+one)
            self.createBtn.Enable()

    def create(self,event):
        if os.path.isfile(self.file):
            ResizeImage(self.file,self.file.replace(".","-result."),self.width,self.height,self.imgType)
            self.showContext.AppendText("成功生成：图片"+self.file.replace(".",'-result.'))
            self.createBtn.Disable()
            self.file=""
        elif len(self.fileList)>0:
            for one in self.fileList:
                ResizeImage(one,one.replace(".","-result."),self.width,self.height,self.imgType)
                self.showContext.AppendText("成功生成：图片"+one.replace(".",'-result.'))
            self.createBtn.Disable()
            self.fileList=[]
    
    def OnDerection(self,event):
        self.imgType=self.radioDerection.GetStringSelection()

'''
filein: 输入图片
fileout: 输出图片
width: 输出图片宽度
height:输出图片高度
type:输出图片类型（png, gif, jpeg...）
'''
def ResizeImage(filein, fileout, width, height, type):
  img = Image.open(filein)
  out = img.resize((width, height),Image.ANTIALIAS)
  #resize image with high-quality
  out.save(fileout, type)

def foundFile(sourceDir,fileNameEnd=None,contain=None,noContain=None,childFound=0,listSize=0):
    '''
    获取目录下文件，不包含子目录
    args:
        dir:文件目录
        fileNameEnd:文件名结尾
        contain:文件名包含
        noContain:文件名不包含
        childFound:是否扫描子目录，0 不扫描（默认），1 扫描
        listSize:扫描多大值返回 0 不设置 其他值设置
    
    return：
        list：物理路径文件名列表
    '''
    if not sourceDir.endswith("\\"):
        sourceDir+="\\"

    list=[]
    for top,dirs,nondirs in os.walk(sourceDir):
        if childFound ==0 and top != sourceDir:       #仅处理当前目录
            continue
        
        for item in nondirs:
            if fileNameEnd is not None:
                if not item.endswith(fileNameEnd) : 
                    continue
            if contain is not None:
                if contain not in item:
                    continue
            
            if noContain is not None:
                if noContain in item:
                    continue
            file=top+item   #得到文件
            list.append(file)
            
            if listSize !=0 and len(list)>=listSize:
                break
    
    return list